package com.sxz.mall.order.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign请求拦截， 处理请求信息  主要包括头信息等（存储于ThreadLocal）
 * 1、如果是新开的线程，新的ThreadLocal拉不到头信息  空指针
 * 解决办法：需要在开启新线程的时候，先获取ServletRequestAttributes并调用
 * RequestContextHolder.setRequestAttributes，传入新线程
 */
@Configuration
public class MallFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                System.out.println("RequestInterceptor:" + Thread.currentThread().getName());
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes)
                        RequestContextHolder.getRequestAttributes();

                HttpServletRequest request = requestAttributes.getRequest();
                String cookie = request.getHeader("Cookie");
                requestTemplate.header("Cookie", cookie);
            }
        };
    }
}
